<template>
  <div class="contract-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>销售合同管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增合同
      </el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="合同编号">
          <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable />
        </el-form-item>
        <el-form-item label="合同名称">
          <el-input v-model="searchForm.contractName" placeholder="请输入合同名称" clearable />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="合同状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已终止" value="terminated" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="searchForm.contractType" placeholder="请选择类型" clearable>
            <el-option label="销售合同" value="sales" />
            <el-option label="服务合同" value="service" />
            <el-option label="框架合同" value="framework" />
            <el-option label="租赁合同" value="lease" />
          </el-select>
        </el-form-item>
        <el-form-item label="签订日期">
          <el-date-picker
            v-model="searchForm.signDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="contractNo" label="合同编号" width="140" fixed="left" />
        <el-table-column prop="contractName" label="合同名称" width="200" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="contractType" label="合同类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getContractTypeColor(row.contractType)" size="small">
              {{ getContractTypeText(row.contractType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contractAmount" label="合同金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.contractAmount?.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="signDate" label="签订日期" width="110" />
        <el-table-column prop="startDate" label="开始日期" width="110" />
        <el-table-column prop="endDate" label="结束日期" width="110" />
        <el-table-column prop="executionProgress" label="执行进度" width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.executionProgress"
              :color="getProgressColor(row.executionProgress)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesperson" label="负责人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" v-if="row.status === 'draft'">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown @command="handleCommand">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'approve', row}" v-if="row.status === 'pending'">
                    审核通过
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'reject', row}" v-if="row.status === 'pending'">
                    审核拒绝
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'execute', row}" v-if="row.status === 'approved'">
                    开始执行
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'complete', row}" v-if="row.status === 'executing'">
                    完成合同
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'terminate', row}" v-if="['approved', 'executing'].includes(row.status)">
                    终止合同
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'renew', row}" v-if="row.status === 'completed'">
                    续签合同
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'download', row}">
                    下载合同
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="contract-form"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同类型" prop="contractType">
                  <el-select v-model="formData.contractType" placeholder="请选择合同类型">
                    <el-option label="销售合同" value="sales" />
                    <el-option label="服务合同" value="service" />
                    <el-option label="框架合同" value="framework" />
                    <el-option label="租赁合同" value="lease" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户名称" prop="customerName">
                  <el-select v-model="formData.customerName" placeholder="请选择客户" filterable>
                    <el-option label="北京科技有限公司" value="北京科技有限公司" />
                    <el-option label="上海贸易集团" value="上海贸易集团" />
                    <el-option label="深圳创新企业" value="深圳创新企业" />
                    <el-option label="广州制造公司" value="广州制造公司" />
                    <el-option label="杭州电商平台" value="杭州电商平台" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同金额" prop="contractAmount">
                  <el-input-number
                    v-model="formData.contractAmount"
                    :min="0"
                    :precision="2"
                    placeholder="请输入合同金额"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="签订日期" prop="signDate">
                  <el-date-picker
                    v-model="formData.signDate"
                    type="date"
                    placeholder="选择签订日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开始日期" prop="startDate">
                  <el-date-picker
                    v-model="formData.startDate"
                    type="date"
                    placeholder="选择开始日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束日期" prop="endDate">
                  <el-date-picker
                    v-model="formData.endDate"
                    type="date"
                    placeholder="选择结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="负责人" prop="salesperson">
                  <el-select v-model="formData.salesperson" placeholder="请选择负责人">
                    <el-option label="张三" value="张三" />
                    <el-option label="李四" value="李四" />
                    <el-option label="王五" value="王五" />
                    <el-option label="赵六" value="赵六" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优先级">
                  <el-select v-model="formData.priority" placeholder="请选择优先级">
                    <el-option label="高" value="high" />
                    <el-option label="中" value="medium" />
                    <el-option label="低" value="low" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="合同条款" name="terms">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="付款方式">
                  <el-select v-model="formData.paymentMethod" placeholder="请选择付款方式">
                    <el-option label="一次性付款" value="lump_sum" />
                    <el-option label="分期付款" value="installment" />
                    <el-option label="预付款" value="advance" />
                    <el-option label="货到付款" value="cod" />
                    <el-option label="月结" value="monthly" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款期限">
                  <el-input-number
                    v-model="formData.paymentDays"
                    :min="0"
                    :max="365"
                    placeholder="请输入付款期限（天）"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="交付方式">
                  <el-select v-model="formData.deliveryMethod" placeholder="请选择交付方式">
                    <el-option label="自提" value="pickup" />
                    <el-option label="送货上门" value="delivery" />
                    <el-option label="物流配送" value="logistics" />
                    <el-option label="邮寄" value="mail" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交付期限">
                  <el-input-number
                    v-model="formData.deliveryDays"
                    :min="0"
                    :max="365"
                    placeholder="请输入交付期限（天）"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="质保期">
              <el-input-number
                v-model="formData.warrantyMonths"
                :min="0"
                :max="120"
                placeholder="请输入质保期（月）"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="违约条款">
              <el-input
                v-model="formData.penaltyClause"
                type="textarea"
                :rows="3"
                placeholder="请输入违约条款"
              />
            </el-form-item>
            <el-form-item label="特殊条款">
              <el-input
                v-model="formData.specialTerms"
                type="textarea"
                :rows="3"
                placeholder="请输入特殊条款"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="附加信息" name="additional">
            <el-form-item label="合同描述">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入合同描述"
              />
            </el-form-item>
            <el-form-item label="风险评估">
              <el-select v-model="formData.riskLevel" placeholder="请选择风险等级">
                <el-option label="低风险" value="low" />
                <el-option label="中风险" value="medium" />
                <el-option label="高风险" value="high" />
              </el-select>
            </el-form-item>
            <el-form-item label="合同附件">
              <el-upload
                class="upload-demo"
                action="#"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="formData.attachments"
                :auto-upload="false"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png/pdf 文件，且不超过 10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="合同详情" width="1200px">
      <div class="contract-detail" v-if="currentContract">
        <el-tabs>
          <el-tab-pane label="基本信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="合同编号">{{ currentContract.contractNo }}</el-descriptions-item>
              <el-descriptions-item label="合同名称">{{ currentContract.contractName }}</el-descriptions-item>
              <el-descriptions-item label="合同类型">
                <el-tag :type="getContractTypeColor(currentContract.contractType)" size="small">
                  {{ getContractTypeText(currentContract.contractType) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="客户名称">{{ currentContract.customerName }}</el-descriptions-item>
              <el-descriptions-item label="合同金额">
                <span class="amount-text">¥{{ currentContract.contractAmount?.toLocaleString() }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="签订日期">{{ currentContract.signDate }}</el-descriptions-item>
              <el-descriptions-item label="开始日期">{{ currentContract.startDate }}</el-descriptions-item>
              <el-descriptions-item label="结束日期">{{ currentContract.endDate }}</el-descriptions-item>
              <el-descriptions-item label="负责人">{{ currentContract.salesperson }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusColor(currentContract.status)" size="small">
                  {{ getStatusText(currentContract.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="执行进度">
                <el-progress
                  :percentage="currentContract.executionProgress"
                  :color="getProgressColor(currentContract.executionProgress)"
                />
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ currentContract.createTime }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="合同条款">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="付款方式">{{ currentContract.paymentMethod || '无' }}</el-descriptions-item>
              <el-descriptions-item label="付款期限">{{ currentContract.paymentDays || 0 }}天</el-descriptions-item>
              <el-descriptions-item label="交付方式">{{ currentContract.deliveryMethod || '无' }}</el-descriptions-item>
              <el-descriptions-item label="交付期限">{{ currentContract.deliveryDays || 0 }}天</el-descriptions-item>
              <el-descriptions-item label="质保期">{{ currentContract.warrantyMonths || 0 }}个月</el-descriptions-item>
              <el-descriptions-item label="风险等级">{{ currentContract.riskLevel || '无' }}</el-descriptions-item>
              <el-descriptions-item label="违约条款" :span="2">{{ currentContract.penaltyClause || '无' }}</el-descriptions-item>
              <el-descriptions-item label="特殊条款" :span="2">{{ currentContract.specialTerms || '无' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="执行记录">
            <el-timeline>
              <el-timeline-item
                v-for="(record, index) in currentContract.executionRecords"
                :key="index"
                :timestamp="record.time"
                :type="record.type"
              >
                <h4>{{ record.title }}</h4>
                <p>{{ record.description }}</p>
                <p v-if="record.operator">操作人：{{ record.operator }}</p>
              </el-timeline-item>
            </el-timeline>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View, Edit, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const activeTab = ref('basic')
const currentContract = ref(null)
const formRef = ref(null)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  contractNo: '',
  contractName: '',
  customerName: '',
  status: '',
  contractType: '',
  signDateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  id: null,
  contractName: '',
  contractType: 'sales',
  customerName: '',
  contractAmount: 0,
  signDate: '',
  startDate: '',
  endDate: '',
  salesperson: '',
  priority: 'medium',
  paymentMethod: 'transfer',
  paymentDays: 30,
  deliveryMethod: 'delivery',
  deliveryDays: 7,
  warrantyMonths: 12,
  penaltyClause: '',
  specialTerms: '',
  description: '',
  riskLevel: 'low',
  attachments: [],
  remark: ''
})

// 表单验证规则
const formRules = {
  contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
  contractAmount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
  signDate: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  salesperson: [{ required: true, message: '请选择负责人', trigger: 'change' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    contractNo: 'HT202401001',
    contractName: '北京科技软件开发合同',
    contractType: 'service',
    customerName: '北京科技有限公司',
    contractAmount: 500000,
    signDate: '2024-01-15',
    startDate: '2024-02-01',
    endDate: '2024-08-01',
    executionProgress: 75,
    status: 'executing',
    salesperson: '张三',
    priority: 'high',
    paymentMethod: 'installment',
    paymentDays: 30,
    deliveryMethod: 'delivery',
    deliveryDays: 7,
    warrantyMonths: 12,
    penaltyClause: '逾期交付按日支付合同金额0.1%的违约金',
    specialTerms: '项目验收后30天内付清尾款',
    description: '企业管理系统开发项目，包含用户管理、权限管理、数据分析等模块',
    riskLevel: 'medium',
    createTime: '2024-01-10 09:30:00',
    remark: '重要项目，需要重点关注进度',
    executionRecords: [
      { time: '2024-01-15', title: '合同签订', description: '双方正式签订合同', operator: '张三', type: 'primary' },
      { time: '2024-02-01', title: '项目启动', description: '项目正式开始执行', operator: '张三', type: 'success' },
      { time: '2024-03-15', title: '第一阶段完成', description: '用户管理模块开发完成', operator: '李四', type: 'success' },
      { time: '2024-05-01', title: '第二阶段完成', description: '权限管理模块开发完成', operator: '王五', type: 'success' }
    ]
  },
  {
    id: 2,
    contractNo: 'HT202401002',
    contractName: '上海贸易设备采购合同',
    contractType: 'sales',
    customerName: '上海贸易集团',
    contractAmount: 800000,
    signDate: '2024-01-20',
    startDate: '2024-01-25',
    endDate: '2024-03-25',
    executionProgress: 100,
    status: 'completed',
    salesperson: '李四',
    priority: 'high',
    paymentMethod: 'advance',
    paymentDays: 15,
    deliveryMethod: 'logistics',
    deliveryDays: 10,
    warrantyMonths: 24,
    penaltyClause: '设备质量问题按设备价值的10%赔偿',
    specialTerms: '设备安装调试由供方负责',
    description: '生产线设备采购，包含主机、辅助设备及配套工具',
    riskLevel: 'low',
    createTime: '2024-01-18 14:20:00',
    remark: '设备已按时交付并验收完成',
    executionRecords: [
      { time: '2024-01-20', title: '合同签订', description: '设备采购合同正式签订', operator: '李四', type: 'primary' },
      { time: '2024-01-25', title: '设备发货', description: '设备从工厂发出', operator: '王五', type: 'success' },
      { time: '2024-02-05', title: '设备到货', description: '设备运抵客户现场', operator: '赵六', type: 'success' },
      { time: '2024-02-15', title: '安装完成', description: '设备安装调试完成', operator: '钱七', type: 'success' },
      { time: '2024-02-20', title: '验收通过', description: '客户验收合格，合同完成', operator: '李四', type: 'success' }
    ]
  },
  {
    id: 3,
    contractNo: 'HT202401003',
    contractName: '深圳创新技术服务合同',
    contractType: 'service',
    customerName: '深圳创新企业',
    contractAmount: 300000,
    signDate: '2024-01-25',
    startDate: '2024-02-01',
    endDate: '2024-12-31',
    executionProgress: 45,
    status: 'executing',
    salesperson: '王五',
    priority: 'medium',
    paymentMethod: 'monthly',
    paymentDays: 30,
    deliveryMethod: 'delivery',
    deliveryDays: 3,
    warrantyMonths: 6,
    penaltyClause: '服务质量不达标按月服务费的20%扣除',
    specialTerms: '每月提供详细服务报告',
    description: '技术咨询和系统维护服务，为期一年',
    riskLevel: 'low',
    createTime: '2024-01-22 11:15:00',
    remark: '长期服务合同，需要定期跟进',
    executionRecords: [
      { time: '2024-01-25', title: '合同签订', description: '技术服务合同签订', operator: '王五', type: 'primary' },
      { time: '2024-02-01', title: '服务开始', description: '技术服务正式开始', operator: '王五', type: 'success' },
      { time: '2024-03-01', title: '第一月服务完成', description: '2月份服务完成，客户满意', operator: '赵六', type: 'success' },
      { time: '2024-04-01', title: '第二月服务完成', description: '3月份服务完成，系统运行稳定', operator: '赵六', type: 'success' }
    ]
  },
  {
    id: 4,
    contractNo: 'HT202401004',
    contractName: '广州制造框架合作协议',
    contractType: 'framework',
    customerName: '广州制造公司',
    contractAmount: 1200000,
    signDate: '2024-01-30',
    startDate: '2024-02-01',
    endDate: '2025-01-31',
    executionProgress: 20,
    status: 'approved',
    salesperson: '赵六',
    priority: 'high',
    paymentMethod: 'monthly',
    paymentDays: 45,
    deliveryMethod: 'pickup',
    deliveryDays: 15,
    warrantyMonths: 18,
    penaltyClause: '年度采购量不足按差额的5%支付违约金',
    specialTerms: '享受批量采购优惠价格',
    description: '年度框架合作协议，预计全年采购金额120万',
    riskLevel: 'medium',
    createTime: '2024-01-28 16:45:00',
    remark: '重要战略合作伙伴',
    executionRecords: [
      { time: '2024-01-30', title: '框架协议签订', description: '年度框架合作协议正式签订', operator: '赵六', type: 'primary' },
      { time: '2024-02-01', title: '合作开始', description: '框架协议生效，开始合作', operator: '赵六', type: 'success' }
    ]
  },
  {
    id: 5,
    contractNo: 'HT202401005',
    contractName: '杭州电商平台推广合同',
    contractType: 'service',
    customerName: '杭州电商平台',
    contractAmount: 150000,
    signDate: '2024-02-01',
    startDate: '2024-02-05',
    endDate: '2024-05-05',
    executionProgress: 0,
    status: 'pending',
    salesperson: '钱七',
    priority: 'medium',
    paymentMethod: 'advance',
    paymentDays: 7,
    deliveryMethod: 'delivery',
    deliveryDays: 1,
    warrantyMonths: 3,
    penaltyClause: '推广效果不达标按推广费的30%扣除',
    specialTerms: '按效果付费，保证最低转化率',
    description: '电商平台营销推广服务，为期3个月',
    riskLevel: 'high',
    createTime: '2024-01-30 10:20:00',
    remark: '新业务类型，需要密切关注效果',
    executionRecords: [
      { time: '2024-02-01', title: '合同提交', description: '推广服务合同提交审核', operator: '钱七', type: 'info' }
    ]
  }
]

// 辅助方法
const getContractTypeColor = (type) => {
  const colorMap = {
    sales: 'primary',
    service: 'success',
    framework: 'warning',
    lease: 'info'
  }
  return colorMap[type] || ''
}

const getContractTypeText = (type) => {
  const textMap = {
    sales: '销售合同',
    service: '服务合同',
    framework: '框架合同',
    lease: '租赁合同'
  }
  return textMap[type] || type
}

const getStatusColor = (status) => {
  const colorMap = {
    draft: 'info',
    pending: 'warning',
    approved: 'primary',
    executing: 'success',
    completed: 'success',
    terminated: 'danger'
  }
  return colorMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    draft: '草稿',
    pending: '待审核',
    approved: '已审核',
    executing: '执行中',
    completed: '已完成',
    terminated: '已终止'
  }
  return textMap[status] || status
}

const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 事件处理方法
const handleAdd = () => {
  dialogTitle.value = '新增合同'
  activeTab.value = 'basic'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑合同'
  activeTab.value = 'basic'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  currentContract.value = row
  viewDialogVisible.value = true
}

const handleCommand = async (command) => {
  const { action, row } = command
  
  try {
    switch (action) {
      case 'approve':
        await ElMessageBox.confirm('确认审核通过该合同？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'approved'
        ElMessage.success('合同审核通过')
        break
      case 'reject':
        await ElMessageBox.confirm('确认拒绝该合同？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'draft'
        ElMessage.success('合同已拒绝，退回修改')
        break
      case 'execute':
        await ElMessageBox.confirm('确认开始执行该合同？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'executing'
        row.executionProgress = 10
        ElMessage.success('合同开始执行')
        break
      case 'complete':
        await ElMessageBox.confirm('确认完成该合同？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'completed'
        row.executionProgress = 100
        ElMessage.success('合同执行完成')
        break
      case 'terminate':
        await ElMessageBox.confirm('确认终止该合同？此操作不可撤销！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        row.status = 'terminated'
        ElMessage.success('合同已终止')
        break
      case 'renew':
        ElMessage.info('跳转到合同续签页面')
        break
      case 'download':
        ElMessage.success('合同文件下载中...')
        break
    }
  } catch {
    // 用户取消操作
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    contractNo: '',
    contractName: '',
    customerName: '',
    status: '',
    contractType: '',
    signDateRange: []
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handlePreview = (file) => {
  console.log('预览文件:', file)
}

const handleRemove = (file, fileList) => {
  console.log('删除文件:', file, fileList)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (formData.id) {
      // 编辑
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        Object.assign(tableData.value[index], {
          ...formData,
          contractNo: tableData.value[index].contractNo,
          createTime: tableData.value[index].createTime
        })
      }
      ElMessage.success('合同信息更新成功')
    } else {
      // 新增
      const newContract = {
        ...formData,
        id: Date.now(),
        contractNo: `HT${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(tableData.value.length + 1).padStart(3, '0')}`,
        executionProgress: 0,
        status: 'draft',
        createTime: new Date().toLocaleString('zh-CN'),
        executionRecords: [
          {
            time: new Date().toLocaleString('zh-CN'),
            title: '合同创建',
            description: '合同草稿创建完成',
            operator: formData.salesperson,
            type: 'info'
          }
        ]
      }
      tableData.value.unshift(newContract)
      pagination.total++
      ElMessage.success('合同创建成功')
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    contractName: '',
    contractType: 'sales',
    customerName: '',
    contractAmount: 0,
    signDate: '',
    startDate: '',
    endDate: '',
    salesperson: '',
    priority: 'medium',
    paymentMethod: 'transfer',
    paymentDays: 30,
    deliveryMethod: 'delivery',
    deliveryDays: 7,
    warrantyMonths: 12,
    penaltyClause: '',
    specialTerms: '',
    description: '',
    riskLevel: 'low',
    attachments: [],
    remark: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const loadData = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    let filteredData = [...mockData]
    
    // 应用搜索过滤
    if (searchForm.contractNo) {
      filteredData = filteredData.filter(item => 
        item.contractNo.toLowerCase().includes(searchForm.contractNo.toLowerCase())
      )
    }
    if (searchForm.contractName) {
      filteredData = filteredData.filter(item => 
        item.contractName.toLowerCase().includes(searchForm.contractName.toLowerCase())
      )
    }
    if (searchForm.customerName) {
      filteredData = filteredData.filter(item => 
        item.customerName.toLowerCase().includes(searchForm.customerName.toLowerCase())
      )
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    if (searchForm.contractType) {
      filteredData = filteredData.filter(item => item.contractType === searchForm.contractType)
    }
    if (searchForm.signDateRange && searchForm.signDateRange.length === 2) {
      const [startDate, endDate] = searchForm.signDateRange
      filteredData = filteredData.filter(item => 
        item.signDate >= startDate && item.signDate <= endDate
      )
    }
    
    pagination.total = filteredData.length
    
    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    tableData.value = filteredData.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.contract-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.amount-text {
  color: #e6a23c;
  font-weight: bold;
}

.contract-form .el-form-item {
  margin-bottom: 20px;
}

.contract-detail {
  margin: 20px 0;
}

.dialog-footer {
  text-align: right;
}

.upload-demo {
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .contract-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>